package com.androidtraining.lab5;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;

import com.example.acamp.dip.R;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class PicDetailFragment extends Fragment {

    public static final String ARG_ITEM_URL = "item_url";
    public static final String ARG_ITEM_NAME = "item_name";

    String mItemURLString;
    String mItemName;

    public PicDetailFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mItemURLString = getArguments().getString(ARG_ITEM_URL);
        mItemName = getArguments().getString(ARG_ITEM_NAME);
		setHasOptionsMenu(true);
    }

    @Override
    public View
            onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.pic_detail, container, false);
        ImageView iv = (ImageView) rootView.findViewById(R.id.pic_detail_pic);
        TextView tv = (TextView) rootView.findViewById(R.id.pic_detail);
        View progressView = rootView.findViewById(R.id.pic_detail_spinner);

        tv.setText(mItemName);
        
        if (null != mItemURLString) {

            if (iv != null) {
            	progressView.setVisibility(View.VISIBLE);
                GetImageTask git = new GetImageTask(iv, progressView);
                git.execute(mItemURLString);
            }
        }
        return rootView;
    }
	/* Checks if external storage is available for read and write */
	public boolean isExternalStorageWritable() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			return true;
		}
		return false;
	}

	public File getFileInAlbumStorageDir(String fileName) {
		File publicDir = Environment
		.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
		if ( !publicDir.exists() ) {
			publicDir.mkdirs();
		}
		File file = new File(
				publicDir,
				fileName);
		return file;
	}

	public File getFileInApplicationAlbumStorageDir(Context context, String fileName) {
		File appDir = context
		.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
		if ( !appDir.exists() ) {
			appDir.mkdirs();
		}
		File file = new File(
				appDir,
				fileName);
		return file;
	}
    
	@SuppressLint("NewApi")
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.toggleLocation:
		{
			((PicListActivity) getActivity()).toggleSaveLocation();
			boolean externalSaveLocation = ((PicListActivity) getActivity())
					.isExternalSaveLocation();
			Toast.makeText(getActivity(), externalSaveLocation ? R.string.toast_using_gallery_storage : R.string.toast_using_application_storage, Toast.LENGTH_SHORT).show();
			if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {
				getActivity().invalidateOptionsMenu();
			}
			return true;
		}
		case R.id.saveItem:
		{
			boolean externalSaveLocation = ((PicListActivity) getActivity())
					.isExternalSaveLocation();
			File file;
			if (externalSaveLocation) {
				file = getFileInAlbumStorageDir(mItemName);
			} else {
				file = getFileInApplicationAlbumStorageDir(getActivity(), mItemName);
			}
			CopyFileFromNetworkTask cft = new CopyFileFromNetworkTask();
			cft.execute(file.toString(), mItemURLString);
			return true;
		}
		}
		return super.onOptionsItemSelected(item);
	}

	public class CopyFileFromNetworkTask extends AsyncTask<String, Void, Boolean> {

		@Override
		protected void onPostExecute(Boolean result) {
			Toast.makeText(getActivity(), result ? R.string.toast_file_copy_complete : R.string.toast_file_copy_failed, Toast.LENGTH_LONG).show();
			super.onPostExecute(result);
		}

		/**
		 * Called with destination, source
		 */
		@Override
		protected Boolean doInBackground(String... params) {

			String destination = params[0];
			String source = params[1];
			BufferedInputStream bis = null;
			BufferedOutputStream bos = null;

			try {
                URL picUrl = new URL(source);
                bis = new BufferedInputStream((InputStream)picUrl.getContent());
				bos = new BufferedOutputStream(new FileOutputStream(destination));
				byte[] buf = new byte[16384];
				int bytesRead;
				while ( -1 !=  (bytesRead = bis.read(buf) ) ) {
		            bos.write(buf, 0, bytesRead);
				}
				return true;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
            	if ( null != bis ) {
            		try {
            			bis.close();
            		} catch (Exception ex) {
            		}
            	}
            	if ( null != bos ) {
            		try {
            			bos.close();
            		} catch (Exception ex) {
            		}
            	}
            }
			return false;
		}

	} // ListAssetsTask

	@Override
	public void onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		getActivity().getMenuInflater().inflate(R.menu.detailmenu, menu);
		MenuItem saveItem = menu.findItem(R.id.saveItem);
		boolean externalSaveLocation = ((PicListActivity) getActivity())
				.isExternalSaveLocation();
		if (externalSaveLocation) {
			saveItem.setTitle(R.string.menu_save_gallery);
		} else {
			saveItem.setTitle(R.string.menu_save_app);
		}
		super.onPrepareOptionsMenu(menu);
	}

    public static final class GetImageTask extends AsyncTask<String, Void, Bitmap> {

    	SoftReference<ImageView> mImageViewRef;
    	SoftReference<View> mProgressViewRef;
    	
        public GetImageTask(ImageView imageView, View progressView) {
        	mImageViewRef = new SoftReference<ImageView>(imageView);
        	mProgressViewRef = new SoftReference<View>(progressView);
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			if ( null != result ) {
				ImageView iv = mImageViewRef.get();
				if ( null != iv ) {
					iv.setImageBitmap(result);
				}
				View progressView = mProgressViewRef.get();
				if ( null != progressView ) {
					progressView.setVisibility(View.GONE);
				}
			}
			super.onPostExecute(result);
		}

		@Override
        protected Bitmap doInBackground(String... params) {
            String picUrlStr = params[0];
            URL picUrl;
            InputStream is = null;
            Bitmap b = null;
            
            try {
                picUrl = new URL(picUrlStr);
                is = (InputStream) picUrl.getContent();
                b = BitmapFactory.decodeStream(is);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
            	if ( null != is ) {
            		try {
            			is.close();
            		} catch (Exception ex) {
            		}
            	}
            }
            return b;
        }
    }

}
